package circuits;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public abstract class Operation implements BooleanValue{

	private Collection<OperationListener> operationListeners;
	protected boolean result;
	protected boolean resultObtained;
	
	public Operation(){
		this.operationListeners = new ArrayList<OperationListener>();
		this.result = false;
		this.resultObtained = false;
	}
	
	protected boolean addOperationListener(OperationListener listener){
		if (! this.operationListeners.contains(listener)){
			this.operationListeners.add(listener);
			return true;
		}
		return false;
	}
	
	protected boolean removeOperationListener(OperationListener listener){
		return this.operationListeners.remove(listener);
	}
	
	protected void fireResultObtained(Operation operation){
		Iterator<OperationListener> operationListenersIterator = this.operationListeners.iterator();
		while (operationListenersIterator.hasNext()){
			OperationListener operationListener = operationListenersIterator.next();
			operationListener.onOperationResultObtained(operation);
		}
	}
	
	protected void setResultAndNotifyListeners(boolean result){
		this.result = result;
		this.resultObtained = true;
		this.fireResultObtained(this);
	}
	
	public boolean getResult(){
		this.getOperandResult();
		return this.result;
	}
	
	@Override
	public boolean getBooleanValue(){
		return this.result;
	}
	
	protected abstract void getOperandResult();
}
